package org.edu.modules.dorm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.base.controller.BaseController;
import org.edu.modules.dorm.entity.*;
import org.edu.modules.dorm.entity.bo.BasicResponseBO;
import org.edu.modules.dorm.entity.bo.VeCampusBO;
import org.edu.modules.dorm.mapper.VeFileFilesMapper;
import org.edu.modules.dorm.service.*;
import org.edu.modules.dorm.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Api(tags = "宿舍分配管理")
@RestController
@RequestMapping("dorm/allotSuShe")
@Slf4j
@ApiSort(value = 100)
public class VeDormSuSheFenPeiController extends BaseController<VeDormStudent, VeDormSuSheFenPeiService> {

    @Autowired
    private VeDormSuSheFenPeiService veDormSuSheFenPeiService;

    @Autowired
    private VeDormSSLouService veDormSSLouService;

    @Autowired
    private VeDormSuSheService mVeDormSuSheService ;

    @Autowired
    private VeDormSuSheAdminService veDormSuSheAdminService;
    @Autowired
    private VeDormDisciplineService veDormDisciplineService;
    @Autowired
    private VeBaseDormManageService veBaseDormManageService; //李少君
    @Autowired
    private VeFileFilesService veFileFilesService; //李少君


    @ApiOperation(value = "宿舍楼信息", notes = "宿舍分配管理-宿舍分配")
    @PostMapping(value = "/SSLInfo")
    public Result<?> SSLInfo() {
        List<VeSuSheFenPeiVo> fpList = new ArrayList<>();
        List<VeDormSSLou> list = veDormSSLouService.getSuSheLou();
        for (int i = 0; i < list.size(); i++) {
            VeSuSheFenPeiVo veSuSheFenPeiVo = new VeSuSheFenPeiVo();
            // 查询所有宿舍信息
            QueryWrapper<VeDormSuShe> wrapper = new QueryWrapper<>() ;
            wrapper.eq("JZWh",list.get(i).getId()) ;
            wrapper.eq("XQH",list.get(i).getXqh()) ;
            List<VeDormSuShe> dorms = mVeDormSuSheService.list(wrapper) ;
            //查询图片url
            QueryWrapper<VeFileFiles> wrapper1 = new QueryWrapper<>() ;
            wrapper1.eq("id",list.get(i).getFileid()) ;
            List<VeFileFiles> url = veFileFilesService.list(wrapper1);
            //宿舍楼有多少个宿舍
            Integer count = veDormSuSheFenPeiService.count(list.get(i).getId());
            //查找宿舍楼宿舍
            List<VeDormFenPeiVo> suSheList = veDormSuSheFenPeiService.selectSuSheLou(list.get(i).getId());
            int kzrs = 0;
            int yzrs = 0;
            for (int i1 = 0; i1 < suSheList.size(); i1++) {

                kzrs = kzrs + suSheList.get(i1).getKzrs();
                yzrs = yzrs + suSheList.get(i1).getYzrs();
            }
            veSuSheFenPeiVo.setId(list.get(i).getId());
            veSuSheFenPeiVo.setJzwmc(list.get(i).getJzwmc());
            veSuSheFenPeiVo.setJzwcs(list.get(i).getJzwcs());
            veSuSheFenPeiVo.setTotalRom(count);
            veSuSheFenPeiVo.setKzrs(kzrs);
            veSuSheFenPeiVo.setYzrs(yzrs);
            veSuSheFenPeiVo.setXbm(list.get(i).getXbm());
            veSuSheFenPeiVo.setFileid(list.get(i).getFileid());
            if(url.size()!=0){
                veSuSheFenPeiVo.setSourcefile(url.get(0).getSourcefile());
            }

            Map<Long,List<VeDormSuShe>> map = dorms.stream().collect(Collectors.groupingBy(VeDormSuShe::getLCH));
            veSuSheFenPeiVo.setMap(map);

            fpList.add(veSuSheFenPeiVo);
        }
        return Result.OK(fpList);
    }

    @ApiOperation(value = "删除学生", notes = "删除学生-宿舍分配")
    @PostMapping(value = "/deleteStudent")

    public Result<?> deleteStudent(@RequestParam(value = "id") Long id,
                                   @RequestParam(value = "dormId") Long dormId) {

        veDormSuSheFenPeiService.removeById(id);
        veDormSuSheFenPeiService.updateYzrs(-1, dormId);
        QueryWrapper<VeDormWeiJi> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", id);
        List<VeDormWeiJi> list = veDormDisciplineService.list(wrapper);
        for (int i = 0; i < list.size(); i++) {
            veDormDisciplineService.removeById(list.get(i).getId());
        }
        return Result.OK("删除成功");
    }


    @ApiOperation(value = "宿舍楼所属宿舍信息", notes = "宿舍分配管理-宿舍分配")
    @PostMapping(value = "/LCInfo")
    public Result<?> LCInfo(@RequestParam(value = "buildId") Integer id) {
        List<VeLcInfoSuSheVo> list = Lists.newArrayList() ;
        List<VeDormssfpVo> dataList = veDormSuSheFenPeiService.getSuSheInfo(id) ;
        if( !CollectionUtils.isEmpty(dataList)){
            Map<String,List<VeDormssfpVo>> map = dataList.stream().collect(
                    Collectors.groupingBy(VeDormssfpVo::getLcname)) ;
            List<VeLcInfoSuSheVo> finalList = list;
            map.forEach((k, v)->{
                VeLcInfoSuSheVo vo = new VeLcInfoSuSheVo() ;
                vo.setLc(k) ;
                vo.setAllSushe(v.size()) ;
                vo.setSleepNum(v.stream().mapToInt(l->l.getKzrs()==null?0:l.getKzrs()).sum()) ;
                vo.setInNum(v.stream().mapToInt(l->l.getYzrs()==null?0:l.getYzrs()).sum()) ;
                vo.setNoInNum(vo.getSleepNum()-vo.getInNum()) ;
                vo.setSuSheList(v.stream().sorted(Comparator.comparing(
                        VeDormssfpVo ::getFjbm
                )).collect(Collectors.toList())) ;
                finalList.add(vo) ;
            });
            list = finalList.stream().sorted(Comparator.comparing(
                    VeLcInfoSuSheVo::getLc
            )).collect(Collectors.toList());
        }
        return Result.OK(list);

    }

    @AutoLog(value = "宿舍分配管理-宿舍分配")
    @ApiOperation(value = "学生宿舍信息", notes = "宿舍分配管理-宿舍分配")
    @PostMapping(value = "/studentDorm")
    public Result<?> studentDorm(@RequestParam(value = "fjbh") Integer fjbh) {

        return Result.OK(veDormSuSheFenPeiService.selectStudent(fjbh));
    }

    @AutoLog(value = "寝室添加学生-宿舍分配")
    @ApiOperation(value = "寝室添加学生", notes = "寝室添加学生-宿舍分配")
    @PostMapping(value = "/addStudent")
    public Result<?> addStudent(@ApiParam("学生id") @RequestParam(value = "stuId") Integer stuId,
                                @ApiParam("房间编号") @RequestParam(value = "fjbh") Long fjbh,
                                @ApiParam("床位号") @RequestParam(value = "cwh") String cwh,
                                @ApiParam("入住时间") @RequestParam(value = "rzsj") Integer rzsj) throws Exception {

        // 查询该学生是否已入住
        QueryWrapper<VeDormStudent> wrapper = new QueryWrapper<>() ;
        wrapper.eq("userId",stuId) ;
        List<VeDormStudent> list =  veDormSuSheFenPeiService.list(wrapper) ;
        if( !CollectionUtils.isEmpty(list)){
            return Result.error("该学生已入住！") ;
        }

        VeDormSShe veDormSShe = veDormSuSheAdminService.getById(fjbh);
        // 判断是否有空床位
        if( veDormSShe.getKzrs() <= veDormSShe.getYzrs() ){
            return Result.error("该房间已住满！") ;
        }

        VeDormStudent veDormStudent = new VeDormStudent();
        veDormStudent.setXQH(veDormSShe.getXqh());
        veDormStudent.setSSLBM(veDormSShe.getJzwh());
        veDormStudent.setLCH(veDormSShe.getLch() + 0L);

        VeBaseStudentVo studentVo = veDormSuSheFenPeiService.getBaseStudent(stuId);

        veDormStudent.setXM(studentVo.getXm());
        veDormStudent.setXH(studentVo.getXh());
        veDormStudent.setCreateUserId(0L);
        veDormStudent.setCreateUserName("管理员");
        veDormStudent.setTerminalId(1L);
        Integer time = (int) System.currentTimeMillis() / 1000;
        veDormStudent.setCreateTime(time);
        veDormStudent.setCWH(cwh);
        veDormStudent.setRZSJ(rzsj);
        veDormStudent.setFJBM(fjbh);
        veDormStudent.setUserId(stuId + 0L);
        veDormSuSheFenPeiService.addStudent(veDormStudent);
        return Result.OK("添加成功");
    }


    @AutoLog(value = "宿舍分配列表查询")
    @ApiOperation(value = "宿舍分配列表查询")
    @PostMapping(value = "/list")
    public Result<?> list(@ApiParam("学生id") @RequestParam(value = "stuId",required = false) Long stuId,
                                @ApiParam("房间编号") @RequestParam(value = "fjbh",required = false) Long fjbh,
                                @ApiParam("宿舍楼号") @RequestParam(value = "SSLH",required = false) Long SSLH,
                                @ApiParam("校区号") @RequestParam(value = "XQH",required = false) Long XQH) throws Exception {
        return Result.OK(veDormSuSheFenPeiService.selectStudentMore(XQH,SSLH,fjbh,stuId));
    }

    @ApiOperation(value = "获取年级下拉框", notes = "获取年级下拉框-宿舍分配")
    @PostMapping(value = "/getGrade")

    public Result<?> getGrade() {
        List<VeBaseGrade> list = veDormSuSheFenPeiService.getGrade();
//        BasicResponseBO<List> list = veBaseDormManageService.getGradeMessage();
//        List<VeBaseGrade> result = JSONObject.parseArray(JSON.toJSONString(list.getResult()), VeBaseGrade.class);
        return Result.OK(list);
    }

    @ApiOperation(value = "获取学院下拉框", notes = "获取学院下拉框-宿舍分配")
    @PostMapping(value = "/getCollege")
    public Result<?> getCollege() {
        List<VeBaseFaculty> list = veDormSuSheFenPeiService.getCollege();
//        BasicResponseBO<List> list = veBaseDormManageService.getFacultyMessage();
//        List<VeBaseFaculty> result = JSONObject.parseArray(JSON.toJSONString(list.getResult()), VeBaseFaculty.class);


        return Result.OK(list);
    }

    @ApiOperation(value = "获取专业下拉框", notes = "获取专业下拉框-宿舍分配")
    @PostMapping(value = "/getMajor")
    public Result<?> getMajor(@ApiParam("学院id") @RequestParam(value = "xyId") Integer xyId) {
        List<VeBaseSpecialty> list = veDormSuSheFenPeiService.getMajor(xyId);
//        BasicResponseBO<List> list = veBaseDormManageService.getSpecialtyMessage(xyId);
//        List<VeBaseSpecialty> result = JSONObject.parseArray(JSON.toJSONString(list.getResult()), VeBaseSpecialty.class);
        return Result.OK(list);
    }

    @ApiOperation(value = "获取班级下拉框", notes = "获取班级下拉框-学生宿舍信息")
    @PostMapping(value = "/getClass")
    public Result<?> Class(@ApiParam("年级id") @RequestParam(value = "gradeId",required = false) Integer gradeId,
                           @ApiParam("专业id") @RequestParam(value = "zyId",required = false) Integer zyId,
                           @ApiParam("学院id") @RequestParam(value = "xyId",required = false) Integer xyId) {
        List<VeBaseBanji> list = veDormSuSheFenPeiService.getBanJi(gradeId, zyId, xyId);
//        BasicResponseBO<List> list = veBaseDormManageService.getBanjiMessage(zyId);
//        List<VeBaseBanji> result = JSONObject.parseArray(JSON.toJSONString(list.getResult()), VeBaseBanji.class);
//        List<VeBaseBanji> result = list.getResult();
        return Result.OK(list);
    }

    @ApiOperation(value = "学生列表选择学生", notes = "学生列表选择学生-宿舍分配")
    @PostMapping(value = "/queryStudent")
    public Result<?> queryStudent(@ApiParam("学号") @RequestParam(value = "xh", required = false) Long xh,
                                  @ApiParam("姓名") @RequestParam(value = "xm", required = false) String xm,
                                  @ApiParam("身份证号") @RequestParam(value = "sfzh", required = false) Long sfzh,
                                  @ApiParam("年级id") @RequestParam(value = "gradeId", required = false) Integer gradeId,
                                  @ApiParam("专业id") @RequestParam(value = "zyId", required = false) Integer zyId,
                                  @ApiParam("学院id") @RequestParam(value = "xyId", required = false) Integer xyId,
                                  @ApiParam("班级id") @RequestParam(value = "bjId", required = false) Integer bjId) {
        List<VeBaseStudentVo> list = veDormSuSheFenPeiService.queryStudent(gradeId, xyId, zyId, bjId, xh, xm, sfzh);
        return Result.OK(list);
    }

    @ApiOperation(value = "学生床位更换", notes = "学生床位更换-宿舍分配")
    @PostMapping(value = "/replaceBed")
    public Result<?> replaceBed(
                                @ApiParam("宿舍编号（宿舍Id）") @RequestParam(value = "sSBH") String sSBH,
                                @ApiParam("学生id") @RequestParam(value = "stuId") String stuId,
                                @ApiParam("宿舍编号（宿舍Id）") @RequestParam(value = "sSBH1") String sSBH1,
                                @ApiParam("学生id") @RequestParam(value = "stuId1") String stuId1
    ) {
        List<VeReplaceBedVo> veReplaceBedVoss = new ArrayList<>();
        VeReplaceBedVo veReplaceBedVoson=new VeReplaceBedVo();
        VeReplaceBedVo veReplaceBedVoson1=new VeReplaceBedVo();
        veReplaceBedVoson.setSSBH(sSBH);
        veReplaceBedVoson.setStuId(stuId);
        veReplaceBedVoss.add(veReplaceBedVoson);
        veReplaceBedVoson1.setSSBH(sSBH1);
        veReplaceBedVoson1.setStuId(stuId1);
        veReplaceBedVoss.add(veReplaceBedVoson1);
       String msg= veDormSSLouService.replaceBed(veReplaceBedVoss);
       if( "success".equals(msg)){
           return Result.OK(msg);
       }
        return Result.error(msg);
    }


    @ApiOperation(value = "宿舍调换")
    @PostMapping(value = "/replaceSuShe")
    public Result<?> replaceBed(
            @ApiParam("宿舍Id") @RequestParam(value = "ssId1") String ssId1,
            @ApiParam("宿舍Id") @RequestParam(value = "ssId2") String ssId2
    ) {
        List<VeReplaceBedVo> veReplaceBedVoss = new ArrayList<>();
        VeReplaceBedVo veReplaceBedVoson=new VeReplaceBedVo();
        VeReplaceBedVo veReplaceBedVoson1=new VeReplaceBedVo();
        veReplaceBedVoson.setSSBH(ssId1);
        veReplaceBedVoss.add(veReplaceBedVoson);
        veReplaceBedVoson1.setSSBH(ssId2);
        veReplaceBedVoss.add(veReplaceBedVoson1);
        String msg= veDormSSLouService.replaceSushe(veReplaceBedVoss);
        if( "success".equals(msg)){
            return Result.OK(msg);
        }
        return Result.error(msg);
    }


}

